package com.barbeque.mall.service.wx;

import com.barbeque.mall.bean.BasePageInfo;
import com.barbeque.mall.bean.advertise.MarketCoupon;
import com.barbeque.mall.bean.advertise.MarketCouponUser;
import com.barbeque.mall.bean.param.CommonData;
import com.barbeque.mall.bean.user.MarketUser;
import com.barbeque.mall.bean.wx.cart.MarketCart;
import com.barbeque.mall.bean.wx.coupon.BO.WxMarketCouponMyListBo;
import com.barbeque.mall.bean.wx.coupon.VO.SelectCouponListVo;
import com.barbeque.mall.bean.wx.coupon.WxMarketCoupon;
import com.barbeque.mall.bean.wx.coupon.WxMarketCouponExample;
import com.barbeque.mall.bean.wx.coupon.WxMarketCouponUser;
import com.barbeque.mall.bean.wx.coupon.WxMarketCouponUserExample;
import com.barbeque.mall.mapper.MarketCartMapper;
import com.barbeque.mall.mapper.MarketCouponMapper;
import com.barbeque.mall.mapper.WxMarketCouponMapper;
import com.barbeque.mall.mapper.WxMarketCouponUserMapper;
import com.barbeque.mall.util.UserInfoUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author bai
 * @since 2022/07/17 02:03
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    WxMarketCouponMapper wxmarketCouponMapper;
    @Autowired
    WxMarketCouponUserMapper wxMarketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    /**
     * 显示优惠券列表的逻辑
     *
     * @param basePageInfo
     * @return
     */
    @Override
    public CommonData<WxMarketCoupon> queryAllCouponList(BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        List<WxMarketCoupon> marketCoupons = wxmarketCouponMapper.selectByExample(null);

        PageInfo<WxMarketCoupon> wxMarketCouponPageInfo = new PageInfo<>(marketCoupons);

        return CommonData.data(wxMarketCouponPageInfo);
    }

    /**
     * 根据用户显示当前用户持有优惠券列表的逻辑
     *
     * @param wxMarketCouponMyListBo
     * @return
     */
    @Override
    public CommonData<WxMarketCoupon> queryMyCouponList(WxMarketCouponMyListBo wxMarketCouponMyListBo) {
        PageHelper.startPage(wxMarketCouponMyListBo.getPage(), wxMarketCouponMyListBo.getLimit());

        WxMarketCouponUserExample wxMarketCouponUserExample = new WxMarketCouponUserExample();

        WxMarketCouponUserExample.Criteria criteria = wxMarketCouponUserExample.createCriteria();

        criteria.andStatusEqualTo(wxMarketCouponMyListBo.getStatus());
        // 通过获取userId进行查询
        MarketUser primaryPrincipal = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();

        criteria.andUserIdEqualTo(userId);

        // 查到此用户持有哪些couponId
        List<WxMarketCouponUser> wxMarketCouponUsers = wxMarketCouponUserMapper.selectByExample(wxMarketCouponUserExample);

        ArrayList<WxMarketCoupon> list = new ArrayList<>();
        for (WxMarketCouponUser wxMarketCouponUser : wxMarketCouponUsers) {
            WxMarketCoupon wxMarketCoupon = wxmarketCouponMapper.selectByPrimaryKey(wxMarketCouponUser.getCouponId());

            if (wxMarketCoupon.getTimeType() == 0) {
                WxMarketCouponUserExample example = new WxMarketCouponUserExample();

                // 根据优惠券id查到信息，可以得到开始结束时间
                WxMarketCouponUserExample.Criteria exampleCriteria = example.createCriteria();
                exampleCriteria.andCouponIdEqualTo(wxMarketCoupon.getId());
                List<WxMarketCouponUser> couponUsers = wxMarketCouponUserMapper.selectByExample(example);

                // 赋值开始结束时间
                for (WxMarketCouponUser couponUser : couponUsers) {
                    wxMarketCoupon.setStartTime(couponUser.getStartTime());
                    wxMarketCoupon.setEndTime(couponUser.getEndTime());
//                    // 获取当前时间
//                    Date date = new Date(System.currentTimeMillis());
//                    // 与结束时间做比较
//                    if(wxMarketCoupon.getEndTime().compareTo(date) == -1){
//                        // 过期了，将status置为1
//                        short i = 1;
//                        wxMarketCoupon.setStatus(i);
//                    }
                }
            }

            list.add(wxMarketCoupon);
        }

        PageInfo<WxMarketCoupon> wxMarketCouponPageInfo = new PageInfo<>(list);

        return CommonData.data(wxMarketCouponPageInfo);
    }

    /**
     * 下单时获取可用优惠券
     *
     * @param cartId
     * @param grouponRulesId
     * @return
     */
    // 根据cartId查到userId
    // 根据userId查到couponId
    // 根据couponId查到对应的优惠券信息
    // 返回值data为对应的优惠券信息
    // 可以写成多表查询
    @Override
    public CommonData<WxMarketCoupon> queryAvailableCoupon(Integer cartId, Integer grouponRulesId) throws ParseException {
        PageHelper.startPage(1, 6);

        // 通过shiro获取到userId
        MarketUser primaryPrincipal = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer userId = primaryPrincipal.getId();

        // 包含couponId
//        WxMarketCouponUserExample wxMarketCouponUserExample = new WxMarketCouponUserExample();
//        WxMarketCouponUserExample.Criteria criteria = wxMarketCouponUserExample.createCriteria();
//        criteria.andUserIdEqualTo(userId);
//        criteria.andDeletedEqualTo(false);
        // 现在的时间早于优惠券结束时间
        //criteria.andEndTimeLessThanOrEqualTo(new Date());
        // 当前用户拥有的所有优惠券
        List<SelectCouponListVo> selectCouponListVos = wxMarketCouponUserMapper.selectByWxExample(userId);
        // 获取到当前时间
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        for (SelectCouponListVo selectCouponListVo : selectCouponListVos) {
            // 如果结束时间大于当前时间，将available置为true
            if(ft.parse(selectCouponListVo.getEndTime()).compareTo(date) == 1 && selectCouponListVo.getStatus() == 0){
                selectCouponListVo.setAvailable(true);

            }
        }

//        ArrayList<SelectCouponListVo> list = new ArrayList<>();
//
//        // 查出对应的优惠券信息并封装
//        for (SelectCouponListVo selectCouponListVo : selectCouponListVos) {
//            list.add(wxmarketCouponMapper.selectByWxPrimaryKey(selectCouponListVo.getCid()));
//        }

        PageInfo<SelectCouponListVo> wxMarketCouponPageInfo = new PageInfo<>(selectCouponListVos);

        return CommonData.data(wxMarketCouponPageInfo);


    }

    /**
     * 领取优惠券的逻辑
     * 查询到当前用户拥有的优惠券列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<WxMarketCouponUser> selectCouponUser(int userId) {
        WxMarketCouponUserExample wxMarketCouponUserExample = new WxMarketCouponUserExample();
        WxMarketCouponUserExample.Criteria criteria = wxMarketCouponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);

        // 包含couponId
        List<WxMarketCouponUser> wxMarketCouponUsers = wxMarketCouponUserMapper.selectByExample(wxMarketCouponUserExample);

        return wxMarketCouponUsers;
    }

    /**
     * 通过couponId将对应的优惠券信息添加进coupon_user
     *
     * @param userId
     * @param couponId
     */
    @Override
    public void insertCouponUserByCouponId(int userId, Integer couponId) {
        // 先根据当前couponId查到需要的优惠券信息
        WxMarketCouponUser wxMarketCouponUser = wxmarketCouponMapper.selectCouponUserInfoBycouponId(couponId);

        if (wxMarketCouponUser.getTimeType() == 0) {
            // 基于领取时间设定开始与结束时间
            Date date = new Date(System.currentTimeMillis());
            wxMarketCouponUser.setStartTime(date);
            Date date2 = new Date(System.currentTimeMillis() + (wxMarketCouponUser.getDays() * 24 * 60 * 60 * 1000));
            wxMarketCouponUser.setEndTime(date2);
        }

        Date date = new Date(System.currentTimeMillis());
        wxMarketCouponUser.setAddTime(date);
        wxMarketCouponUser.setUpdateTime(date);

        wxMarketCouponUser.setUserId(userId);

        wxMarketCouponUserMapper.insertSelective(wxMarketCouponUser);
    }

    /**
     * 查询coupon表中此种优惠券的库存的逻辑
     *
     * @param couponId
     * @return
     */
    @Override
    public WxMarketCoupon queryCouponTotalByCouponId(Integer couponId) {
        WxMarketCoupon wxMarketCoupon = wxmarketCouponMapper.selectByPrimaryKey(couponId);

        return wxMarketCoupon;
    }

    /**
     * 减优惠券库存的逻辑
     *
     * @param
     */
    @Override
    public void updateCouponTotalByCouponId(WxMarketCoupon wxMarketCoupon) {
        if (wxMarketCoupon.getTotal() > 1) {
            wxMarketCoupon.setTotal(wxMarketCoupon.getTotal() - 1);
            wxmarketCouponMapper.updateTotalByPrimaryKey(wxMarketCoupon);
        } else if (wxMarketCoupon.getTotal() == 1) {
            wxMarketCoupon.setTotal(-1);
            wxmarketCouponMapper.updateTotalByPrimaryKey(wxMarketCoupon);
        }

    }

    /**
     * 优惠券通过兑换码兑换的逻辑
     *
     * @param code
     * @return
     */
    @Override
    public WxMarketCoupon queryCouponByCode(String code) {
        WxMarketCoupon wxMarketCoupon = wxmarketCouponMapper.selectByCode(code);

        return wxMarketCoupon;

    }

    /**
     * 获取所有优惠券
     *
     * @return java.util.List<com.barbeque.mall.bean.advertise.MarketCoupon>
     * @author 苏东宇
     * @since 2022/07/21 9:24
     */
    @Override
    public List<WxMarketCoupon> getCouponList() {
        PageHelper.startPage(1, 3);
        List<WxMarketCoupon> wxMarketCoupons = wxmarketCouponMapper.selectByExample(null);


        return wxMarketCoupons;
    }


//    /**
//     * 添加优惠券信息的逻辑
//     * @param
//     * @return
//     */
//    @Override
//    public MarketCoupon insertCouponInfo(MarketCoupon marketCoupon) {
//        // 插入一条数据
//        marketCouponMapper.insertSelective(marketCoupon);
//        // 根据id，将插入的数据查询出来
//        marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCoupon.getId());
//
//        // 添加时间
//        Date date = new Date();
//        marketCoupon.setAddTime(date);
//        marketCoupon.setUpdateTime(date);
//
//        return marketCoupon;
//
//    }
//
//    /**
//     * 更新优惠券信息的逻辑
//     * @param marketCoupon
//     * @return
//     */
//    @Override
//    public MarketCoupon updateCouponInfo(MarketCoupon marketCoupon) {
//        // 更新操作
//       marketCouponMapper.updateByPrimaryKeySelective(marketCoupon);
//       // 将更新的数据查出来，作为返还给前端的数据
//       marketCoupon = marketCouponMapper.selectByPrimaryKey(marketCoupon.getId());
//
//        Date date = new Date();
//        marketCoupon.setUpdateTime(date);
//        return marketCoupon;
//    }
//
//    /**
//     * 删除一条优惠券信息的逻辑
//     * @param marketCoupon
//     */
//    @Override
//    public void deleteCouponInfo(MarketCoupon marketCoupon) {
//        marketCouponMapper.deleteByPrimaryKey(marketCoupon.getId());
//    }
//
//    /**
//     * 根据id查询优惠券信息的逻辑(详情)
//     * @param id
//     * @return
//     */
//    @Override
//    public MarketCoupon queryCouponInfoById(Integer id) {
//        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(id);
//
//        return marketCoupon;
//    }
//
//    /**
//     * 根据优惠券id查询持有此优惠券的用户
//     * @param couponListUserBo
//     * @return
//     */
//    @Override
//    public CommonData<WxMarketCouponUser> querryCouponListUserByCouponId(CouponListUserBo couponListUserBo) {
//        PageHelper.startPage(couponListUserBo.getPage(),couponListUserBo.getLimit());
//
//        // 条件查询
//        WxMarketCouponUserExample marketCouponUserExample = new WxMarketCouponUserExample();
//        WxMarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
//        criteria.andCouponIdEqualTo(couponListUserBo.getCouponId());
//        List<WxMarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
//
//
//        PageInfo<WxMarketCouponUser> marketCouponUserPageInfo = new PageInfo<>(marketCouponUsers);
//
//        return CommonData.data(marketCouponUserPageInfo);
//    }
//
//    /**
//     * 优惠券的模糊查询逻辑
//     * @param couponListBo
//     * @return
//     */
//    @Override
//    public CommonData<MarketCoupon> queryCouponListByCondition(CouponListBo couponListBo) {
//        PageHelper.startPage(couponListBo.getPage(),couponListBo.getLimit());
//
//        MarketCouponExample marketCouponExample = new MarketCouponExample();
//        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
//        if(couponListBo.getName() != null){
//            criteria.andNameLike("%" + couponListBo.getName() + "%");
//        }
//        if(couponListBo.getStatus() != null){
//            criteria.andStatusEqualTo(couponListBo.getStatus());
//        }
//        if(couponListBo.getType() != null){
//            criteria.andGoodsTypeEqualTo(couponListBo.getType());
//        }
//
//        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
//
//        PageInfo<MarketCoupon> marketCouponPageInfo = new PageInfo<>(marketCoupons);
//
//        return CommonData.data(marketCouponPageInfo);
//    }
//
//    /**
//     * 对优惠券持有人的模糊查询操作
//     * @param couponListUserBo
//     * @return
//     */
//    @Override
//    public CommonData<WxMarketCouponUser> querryCouponListUserCondition(CouponListUserBo couponListUserBo) {
//        PageHelper.startPage(couponListUserBo.getPage(),couponListUserBo.getLimit());
//
//        WxMarketCouponUserExample marketCouponUserExample = new WxMarketCouponUserExample();
//        WxMarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
//        if(couponListUserBo.getUserId() != null){
//            criteria.andUserIdEqualTo(couponListUserBo.getUserId());
//        }
//        if(couponListUserBo.getStatus() != null){
//            criteria.andStatusEqualTo(couponListUserBo.getStatus());
//        }
//
//        List<WxMarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
//
//        PageInfo<WxMarketCouponUser> marketCouponUserPageInfo = new PageInfo<>(marketCouponUsers);
//
//        return CommonData.data(marketCouponUserPageInfo);
//    }

}
